﻿#if NETCOREAPP3_0
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json;
#else
using Newtonsoft.Json;
#endif
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Bootstrap.Security
{
    internal class BootstrapAdminHttpClient
    {
        private readonly HttpClient _client;

        public BootstrapAdminHttpClient(HttpClient client) => _client = client;

#if NETCOREAPP3_0
        public async Task<T> PostAsJsonAsync<T>(string requestUri, object postData, JsonSerializerOptions options = null)
#else
        public async Task<T> PostAsJsonAsync<T>(string requestUri, object postData)
#endif
        {
            var ret = default(T);
            try
            {
#if NETCOREAPP3_0
                if (options == null) options = new JsonSerializerOptions().AddDefaultConverters();

                var sc = new StringContent(JsonSerializer.Serialize(postData, options));
#else
                var sc = new StringContent(JsonConvert.SerializeObject(postData));
#endif
                sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var result = await _client.PostAsync(requestUri, sc);
                if (result.IsSuccessStatusCode)
                {
                    var content = await result.Content.ReadAsStringAsync();
#if NETCOREAPP3_0
                    ret = JsonSerializer.Deserialize<T>(content, options);
#else
                    ret = JsonConvert.DeserializeObject<T>(content);
#endif
                }
            }
            catch { }
            return ret;
        }
    }
}
